<script setup lang="ts">
import { h, onMounted, ref } from 'vue';
import {NButton, NSpace, useDialog} from 'naive-ui';
import type { DataTableColumns, FormInst, FormRules, UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui';
import Step01Img from '@/assets/duplicate-check/step-01.png';
import Step02Img from '@/assets/duplicate-check/step-02.png';
import Step03Img from '@/assets/duplicate-check/step-03.png';
import { generateRandomCode, successMessage, warningMessage } from '@/utils/utils';
import {
  bidCompareInsertAction,
  bidCompareInsertUnitAction,
  documentRunFunctionsAction,
  getCheckContentListAction,
  insertCompareContentAction, msgCheckAction,
  uploadCompareFileAction,
  uploadDocument2DocxAction, uploadDocument2DocxNewAction
} from '@/service/api';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { USER_INFO } from '@/utils/const';

const { routerPushByKey } = useRouterPush();

const showLoading = ref<boolean>(false);
const loadingDes = ref<string>('正在为您分析招标文件，请耐心等待...');

const topStepList = ref<any[]>([
  {
    id: generateRandomCode(3, 'num'),
    title: '检测设置',
    describe: '设置检测规则',
    icon: Step01Img
  },
  {
    id: generateRandomCode(3, 'num'),
    title: '上传对比文件',
    describe: '提交检测',
    icon: Step02Img
  },
  {
    id: generateRandomCode(3, 'num'),
    title: '检测报告',
    describe: '查看报告',
    icon: Step03Img
  }
]);

onMounted(() => {
  getCheckContentListData();
});

const checkContentList = ref<any[]>([]);

// 获取检查内容列表
async function getCheckContentListData() {
  const { data, error } = await getCheckContentListAction();
  if (!error) {
    checkContentList.value = data;
  }
}

interface FormType {
  checkName: string; // 检查名称
  isFilter: number; // 是否过滤招标
  functionList: string[]; // 检查内容
}

const formData = ref<FormType>({
  checkName: '',
  isFilter: 2,
  functionList: []
});

const formRef = ref<FormInst | null>(null);

// 校验规则
const rules: FormRules = {
  checkName: {
    required: true,
    message: '请输入检查名称',
    trigger: ['input', 'blur']
  },
  functionList: {
    type: 'array',
    required: true,
    message: '请选择检查内容',
    trigger: 'change'
  }
};

const docFilePath = ref<string>('');
const docFileName = ref<string>('');

const fileTypeList: string[] = [
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/pdf'
];

// 过滤文件上传
const customFileRequest = async ({ file, onFinish }: UploadCustomRequestOptions) => {
  if (!fileTypeList.includes(file.type)) {
    warningMessage('请上传doc，docx或pdf格式的文档');
    return;
  }

  // console.log('file: ', file);

  // docx格式文件直接上传
  if (file.type === fileTypeList[1]) {
    const formData = new FormData();
    formData.append('uploadFiles', file.file as Blob);

    const { data, error } = await uploadCompareFileAction(formData);
    showLoading.value = false;
    if (!error) {
      docFilePath.value = data[0].filePath;
      docFileName.value = file.name.substring(0, file.name.lastIndexOf('.'));
      successMessage('上传成功');
      onFinish();
    }
  } else {
    const formData = new FormData();
    formData.append('upload', file.file as Blob);

    showLoading.value = true;
    loadingDes.value = '招标文件上传中，请耐心等待...';
    const { data, error } = await uploadDocument2DocxAction(formData);
    showLoading.value = false;
    // console.log('上传文件返回结果', data);
    if (!error) {
      docFilePath.value = data.file_path[0];
      docFileName.value = file.name.substring(0, file.name.lastIndexOf('.'));
      successMessage('上传成功');
      onFinish();
    }
  }
};

// 移除上传的过滤文件
function removeFileHandle() {
  docFilePath.value = '';
  docFileName.value = '';
}

type RowData = {
  id: number;
  name: string;
  url: string;
};

const uploadFileList = ref<UploadFileInfo[]>([]);
const fileList = ref<UploadFileInfo[]>([]);
const changeFileList = ref<UploadFileInfo[]>([]);

// 招标文件上传
const bidCustomFileRequest = async ({ file, onFinish }: UploadCustomRequestOptions) => {
  if (!fileTypeList.includes(file.type)) {
    warningMessage('请上传doc，docx或pdf格式的文档');
    return;
  }

  showLoading.value = true;
  loadingDes.value = '招标文件上传中，请耐心等待...';

  const formData = new FormData();
  formData.append('uploadFiles', file.file as Blob);

  const { data, error } = await uploadCompareFileAction(formData);
  if (!error) {
    const fileObj: any = {
      id: file.id,
      file: file.file,
      fullPath: file.fullPath,
      percentage: file.percentage,
      url: data[0].filePath,
      name: data[0].fileCname,
      status: 'finished',
      batchId: file.batchId,
      type: file.type,
      thumbnailUrl: file.thumbnailUrl
    };

    uploadFileList.value.push(fileObj);
  }

  const changeFormData = new FormData();
  changeFormData.append('upload', file.file as Blob);

  const { data: changeData, error: changeError } = await uploadDocument2DocxAction(changeFormData);
  // console.log('上传文件返回结果', data);
  if (!changeError) {
    successMessage('上传成功');

    const changeFileObj: any = {
      id: file.id,
      file: file.file,
      fullPath: file.fullPath,
      percentage: file.percentage,
      url: changeData.file_path[0],
      name: file.name.substring(0, file.name.lastIndexOf('.')),
      splitFiles: changeData.split_files[0].split,
      status: 'finished',
      batchId: file.batchId,
      type: file.type,
      thumbnailUrl: file.thumbnailUrl
    };

    changeFileList.value.push(changeFileObj);

    if (changeFileList.value.length === uploadFileList.value.length) {
      showLoading.value = false;
    }

    onFinish();
  }

  // console.log('fileList: ', fileList.value);
  // console.log('uploadFileList: ', uploadFileList.value);
};

const columns: DataTableColumns<RowData> = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render(item: RowData, index: number) {
      return index + 1;
    }
  },
  {
    title: '文件名称',
    key: 'name',
    align: 'center',
    ellipsis: 'EllipsisProps'
  },
  {
    title: '操作',
    key: '',
    width: 120,
    align: 'center',
    render(item: RowData) {
      return h(
        NSpace,
        { justify: 'center' },
        {
          default: () => [
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                size: 'small',
                style:
                  'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 14px; color: #FF6E6E;',
                onClick: () => {
                  removeBidFileHandle(item);
                }
              },
              { default: () => '删除' } // 按钮显示名称
            )
          ]
        }
      );
    }
  }
];

// 移除上传的招标文件
function removeBidFileHandle(item: RowData) {
  // uploadFileList.value = uploadFileList.value.filter((fileItem: any) => fileItem.id !== item.id);
  fileList.value = fileList.value.filter((fileItem: any) => fileItem.id !== item.id);
  // changeFileList.value = changeFileList.value.filter((fileItem: any) => fileItem.id !== item.id);
  // console.log('删除后fileList: ', fileList.value, changeFileList.value);
}

// 查看检测记录
function viewDetectionRecordsClick() {
  routerPushByKey('bid-materials', {
    query: {
      tab: '4'
    }
  });
}

const dialog = useDialog();

// 开始检查
function startCheckingClick() {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      if (formData.value.isFilter === 1 && docFilePath.value === '') {
        warningMessage('请上传招标过滤文件');
        return;
      }

      if (fileList.value.length === 0) {
        warningMessage('请上传招标文件');
        return;
      }

      if (fileList.value.length < 2) {
        warningMessage('请至少上传2个招标文件');
        return;
      }

      for (let i: number = 0; i < fileList.value.length; i++) {
        const file: UploadFileInfo = fileList.value[i];
        if (!fileTypeList.includes(file.type)) {
          warningMessage('请上传doc，docx或pdf格式的招标文件');
          return;
        }
      }

      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: `${formData.value.checkName}`
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `检查名称中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const fileNameList: string[] = [];
      const fileFormData = new FormData();
      for (let i: number = 0; i < fileList.value.length; i++) {
        const file: UploadFileInfo = fileList.value[i];
        fileNameList.push(file.name.substring(0, file.name.lastIndexOf('.')));
        fileFormData.append('uploadFiles', file.file as Blob);
      }

      loadingDes.value = '小主，招标文件正在上传中，请耐心等待...';
      showLoading.value = true;
      const { data: uploadData, error: uploadError } = await uploadCompareFileAction(fileFormData);
      if (!uploadError) {
        for (let i: number = 0; i < uploadData.length; i++) {
          const fileData: any = uploadData[i];
          const fileObj: any = {
            id: fileData.id,
            url: fileData.filePath,
            name: fileData.fileCname
          };

          uploadFileList.value.push(fileObj);
        }
      }

      const filePathList: string[] = [];
      for (let i: number = 0; i < uploadFileList.value.length; i++) {
        filePathList.push(uploadFileList.value[i].url);
      }

      console.log('uploadFileList: ', uploadFileList.value);

      const changeParams: any = {
        file_path: filePathList
      };

      loadingDes.value = '小主，招标文件正在解析中，请耐心等待...';
      const { data: changeData, error: changeError } = await uploadDocument2DocxNewAction(changeParams);
      // console.log('上传文件返回结果', data);
      if (!changeError) {
        for (let i: number = 0; i < changeData.split_files.length; i++) {
          const splitFile: any = changeData.split_files[i];
          const changeFileObj: any = {
            url: splitFile.file,
            name: fileNameList[i],
            splitFiles: splitFile.split
          };

          changeFileList.value.push(changeFileObj);
        }
      }

      const changeFilePathList: string[] = [];
      for (let i: number = 0; i < changeFileList.value.length; i++) {
        changeFilePathList.push(changeFileList.value[i].url);
      }

      // console.log('filePathList: ', filePathList);
      // console.log('changeFilePathList: ', changeFilePathList);

      const functions: number[] = [];
      for (let i: number = 0; i < formData.value.functionList.length; i++) {
        functions.push(Number.parseInt(formData.value.functionList[i], 10));
      }

      loadingDes.value = '小主，文档正在对比中，请耐心等待...';
      const userInfo = localStg.get(USER_INFO);
      const params: any = {
        tenantId: userInfo!.user.tenantId,
        userId: userInfo!.user.userId,
        title: formData.value.checkName,
        filePath: docFilePath.value,
        checkContent: functions.join(','),
        isFilter: formData.value.isFilter
      };
      const { data, error } = await bidCompareInsertAction(params);

      if (!error) {
        const compareParams: any = {
          function: functions, // 选择哪些功能的数组，按int数字序号依次对应
          zhaobiao_path: docFilePath.value, // 招标文档
          file_path: changeFilePathList,
          file_path_origin: filePathList
        };

        const { data: checkResult, error: checkError } = await documentRunFunctionsAction(compareParams);
        if (!checkError) {
          const fileParams: any[] = [];
          for (let i: number = 0; i < changeFileList.value.length; i++) {
            const changeFileObj: any = changeFileList.value[i];
            fileParams.push({
              logId: data.id,
              bidUnit: changeFileObj.name,
              unitPath: changeFileObj.url,
              number: i + 1,
              splitFiles: changeFileObj.splitFiles
            });
          }
          const { data: fileResult, error: fileError } = await bidCompareInsertUnitAction(fileParams);
          console.log('插入文件结果', fileResult);
          if (!fileError) {
          }
          const contentMaps: any[] = [];
          const ignoreKeyList: string[] = [
            'evaluate_time',
            'total_mix_number',
            'total_file_character',
            'total_file_image',
            'total_file_number'
          ];
          for (const contentObj in checkResult) {
            // 确保只枚举对象自身的属性
            if (Object.hasOwn(checkResult, contentObj)) {
              if (!ignoreKeyList.includes(contentObj)) {
                const mapObj: any = {
                  [contentObj]: checkResult[contentObj]
                };
                contentMaps.push(mapObj);
              }
            }
          }

          const resultParams: any = {
            evaluateTime: checkResult.evaluate_time,
            logId: data.id,
            totalMixNumber: checkResult.total_mix_number,
            totalFileCharacter: checkResult.total_file_character,
            totalFileImage: checkResult.total_file_image,
            totalFileNumber: checkResult.total_file_number,
            maps: contentMaps
          };

          const { data: resultResult, error: resultError } = await insertCompareContentAction(resultParams);
          showLoading.value = false;
          if (!resultError) {
          }

          const pushParams: any = {
            createType: 1,
            logId: data.id,
            compareName: formData.value.checkName
          };

          await routerPushByKey('duplicate-check_check-result', { query: pushParams });
        }
      }
    }
  });
}
</script>

<template>
  <NSpin :show="showLoading" :description="loadingDes" :rotate="false" size="large">
    <template #icon>
      <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
    </template>
    <div class="document-layout min-h-500px flex flex-col gap-16px lt-sm:overflow-auto">
      <div class="flex flex-row justify-between">
        <div class="flex items-baseline">
          <span class="tag-title">火眼金睛</span>
          <span class="tag-text">(辅助判断投标异常行为的检测工具)</span>
        </div>
        <NButton class="history-btn" text :bordered="false" @click="viewDetectionRecordsClick">检测记录></NButton>
      </div>
      <div class="top-box">
        <div v-for="(item, index) in topStepList" :key="item.id" class="top-item">
          <div class="flex flex-row items-center">
            <img :src="item.icon" :alt="item.title" width="55" height="64" />
            <div class="ml-55px flex flex-col items-center">
              <span class="step-title">{{ item.title }}</span>
              <span class="step-describe">{{ item.describe }}</span>
            </div>
          </div>
          <div v-if="index !== 2" class="step-line"></div>
        </div>
      </div>
      <div class="flex items-center">
        <div class="left-box">
          <div class="title-text mb-15px">第一步: 检测设置</div>
          <NScrollbar class="max-h-450px pr-15px">
            <NForm
              ref="formRef"
              :model="formData"
              :rules="rules"
              size="large"
              require-mark-placement="left"
              label-placement="left"
              label-width="120"
            >
              <NFormItem
                label="检查名称"
                label-style="font-size: 18px; font-family: HarmonyOS Sans SC;"
                path="checkName"
              >
                <NInput v-model:value="formData.checkName" :maxlength="50" placeholder="请输入检查名称" />
              </NFormItem>
              <NFormItem
                label="检查是否过滤招标文件"
                label-style="font-size: 18px; font-family: HarmonyOS Sans SC;"
                :required="formData.isFilter === 1"
              >
                <div class="flex-col">
                  <NRadioGroup v-model:value="formData.isFilter" name="radiogroup">
                    <NSpace>
                      <NRadio name="是" :value="1">是</NRadio>
                      <NRadio name="否" :value="2">否</NRadio>
                      <span v-if="formData.isFilter === 2" class="filter-tips">
                        *招标文件中出现的内容不参与查重检测
                      </span>
                    </NSpace>
                  </NRadioGroup>
                  <div v-if="formData.isFilter === 1" class="mt-12px flex items-center">
                    <div class="w-300px">
                      <NUpload
                        directory-dnd
                        :max="1"
                        accept=".doc, .docx, .pdf"
                        :custom-request="customFileRequest"
                        @remove="removeFileHandle"
                      >
                        <NUploadDragger>
                          <div class="mb-12px w-full flex-y-center justify-center">
                            <img src="@/assets/duplicate-check/file-upload.png" alt="" width="47" height="43" />
                          </div>
                          <div class="flex items-center justify-center">
                            <NText class="font-size-18px color-#333333">导入招标文件</NText>
                          </div>
                          <NP class="mt-6px font-size-16px" depth="3">支持doc、docx、pdf格式</NP>
                        </NUploadDragger>
                      </NUpload>
                    </div>
                    <span class="upload-tips">(仅支持单文件上传)</span>
                  </div>
                </div>
              </NFormItem>
              <NFormItem
                label="检查内容"
                label-style="font-size: 18px; font-family: HarmonyOS Sans SC;"
                path="functionList"
              >
                <div class="w-full bg-white p-24px">
                  <NCheckboxGroup v-model:value="formData.functionList">
                    <NSpace>
                      <NCheckbox
                        v-for="(item, index) in checkContentList"
                        :key="item.dictValue"
                        :value="item.dictValue"
                      >
                        {{ item.dictLabel }}
                      </NCheckbox>
                    </NSpace>
                  </NCheckboxGroup>
                </div>
              </NFormItem>
            </NForm>
          </NScrollbar>
        </div>
        <div class="right-box">
          <div class="mb-15px w-full flex items-center justify-between">
            <div class="flex flex-col">
              <div class="title-text">第二步: 导入对比文件</div>
              <span class="right-tips">
                提示:目前最多支持选择5个单位(每个文件默认1个单位)，如果需要更多单位，请联系我们
              </span>
            </div>
            <NUpload
              v-model:file-list="fileList"
              :max="5"
              multiple
              :show-file-list="false"
              accept=".doc, .docx, .pdf"
              :default-upload="false"
            >
              <NButton class="upload-btn" :bordered="false">
                <template #icon>
                  <img src="@/assets/duplicate-check/icon-upload.png" width="64" height="64" alt="" />
                </template>
                上传投标文件
              </NButton>
            </NUpload>
          </div>
          <NDataTable :columns="columns" :data="fileList" :row-key="(item: any) => item.id" max-height="300" />
        </div>
      </div>
      <NSpace justify="center">
        <NButton class="create-button" text :bordered="false" @click="startCheckingClick">开始检查</NButton>
      </NSpace>
    </div>
  </NSpin>
</template>

<style scoped lang="scss">
.bg-layout {
  padding: 16px 26px 0 !important;
  background: url('@/assets/smart-eye/smart-bg.png') no-repeat;
  background-size: 100% 100%;
}
:deep(.n-spin) {
  width: auto;
  height: auto;
}
.tag-title {
  font-weight: bold;
  font-size: 28px;
  color: #333333;
  line-height: 48px;
}
.tag-text {
  margin-left: 14px;
  font-weight: 400;
  font-size: 20px;
  color: #ff7575;
  line-height: 48px;
}
.history-btn {
  font-weight: 400;
  font-size: 20px;
  color: #333333 !important;
  line-height: 48px;
}
.top-box {
  padding: 0 33px;
  width: 100%;
  height: 120px;
  background: url('@/assets/duplicate-check/top-bg.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .top-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    overflow: hidden;
    flex: 1;
    .step-title {
      width: 145px;
      font-weight: bold;
      font-size: 24px;
      color: #333333;
      text-align: center;
    }
    .step-describe {
      width: 145px;
      margin-top: 5px;
      font-weight: 400;
      font-size: 20px;
      color: #333333;
      text-align: center;
    }
    .step-line {
      margin: 0 95px;
      width: calc(100% - 145px - 110px);
      height: 1px;
      background: #bfc1c5;
    }
  }
  .top-item:last-child {
    flex: none;
  }
}
.left-box {
  width: calc((100% - 24px) / 2);
  height: 525px;
  background: url('@/assets/duplicate-check/left-bg.png') no-repeat;
  background-size: 100% 100%;
  padding: 28px 13px 28px;
  display: flex;
  flex-direction: column;
  .filter-tips {
    font-weight: 400;
    font-size: 14px;
    color: #ff7575;
    line-height: 14px;
  }
}
.upload-tips {
  margin-left: 18px;
  width: 200px;
  font-weight: 400;
  font-size: 14px;
  color: #ff7575;
  line-height: 14px;
}
.right-box {
  margin-left: 24px;
  width: calc((100% - 24px) / 2);
  height: 525px;
  background: url('@/assets/duplicate-check/right-bg.png') no-repeat;
  background-size: 100% 100%;
  padding: 28px;
  display: flex;
  flex-direction: column;
  .right-tips {
    margin-top: 10px;
    font-weight: 400;
    font-size: 16px;
    color: #ff7575;
    line-height: 24px;
  }
  .upload-btn {
    width: 180px;
    height: 54px;
    background: linear-gradient(46deg, #e877ae, #7c73f3);
    border-radius: 6px;
    font-weight: 500 !important;
    font-size: 18px;
    color: #ffffff !important;
  }
}
:deep(.n-upload-file-list .n-upload-file .n-upload-file-info .n-upload-file-info__name) {
  flex: 0.9;
}
:deep(.n-data-table-tr) {
  background-color: #dfdefd !important;
}
:deep(.n-data-table-th) {
  background-color: transparent;
}
:deep(.n-data-table-th__title) {
  font-weight: 500;
  font-size: 18px;
  color: #666666;
}
:deep(.n-upload) {
  width: auto;
}
.title-text {
  font-weight: bold;
  font-size: 20px;
  color: #333333;
}
.create-button {
  font-weight: 500 !important;
  font-size: 24px;
  color: #ffffff !important;
  width: 475px;
  height: 72px;
  background: linear-gradient(46deg, #e877ae, #7c73f3);
  border-radius: 6px;
}
</style>
